<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class importexport_tasks_runimport extends base_task_abstract implements base_interface_task{

    const TTL = 86400;//缓存时间
    const REDIS_DB = 1;

    public function exec($params=null){
        set_time_limit(3600);

        $taskModel = app::get('importexport')->model('task');
        //执行队列，更新队列状态
        $taskModel->update(array('status'=>4),array('key'=>$params['key']));
       // $redis = kernel::single('base_kvstore_redis2');

        $redis = new Redis();
        $redis->connect('127.0.0.1');
        $redis->select(1);

        $key = $pieces = explode("-", $params['key']);
        $o = kernel::single($params['model']);

        $dataObj = kernel::single('importexport_data_object',$params['model']);
        $count = $redis->lLen($params['key']);
        $message = '';
        for($i = 0;$i<$count;$i++){
            $rows = $redis->rpop($params['key']);
            $rows = unserialize($rows);
            $msg = null;
            //实例化数据类
             $rs = $dataObj->dataToSdf($rows,$msg);
             if( $msg['error'] ){
                $msg['number'] =  $i+1 + ($key[2]*500);
                $message = '第'.$msg['number'].'行:'.$msg['error'].chr(13).chr(10).$message;
                $redis->lPush($params['key'].'_data_error',serialize($msg));
                $redis->expire($params['key'].'_data_error',self::TTL);
            }else{
                $flag =  $o->save($rs);

                 $type_id =2;
                 cachemgr::co_start();
                 $goodsInfoType = app::get("b2c")->model("goods_type")->dump2(array('type_id'=>$type_id) );
                 cachemgr::set("goodsObjectType".$type_id, $goodsInfoType, cachemgr::co_end());

                 if( !$flag ){
                    $redis->lPush($params['key'].'_insert_error',serialize($rows));
                    exit;
                }else{
                    $redis->lPush($params['key'].'_complate',serialize($rows));
                    $redis->expire($params['key'].'_complate',self::TTL);
                }
            }
        }

        if($message){
            if($redis->lLen($params['key'].'_complate')){
                $params['status'] = $params['status']  = 8;
            }else{
                $params['status'] = $params['status'] = 6;
            }
        }else{
            $params['status'] = $params['status'] = 5;
        }
        if($message){
            $redis->set($params['key'].'_error_message',$message);
        }

        $msg = '共'.$count.'条,'.'完成'.$redis->lLen($params['key'].'_complate').'条';
        $taskModel->update(array('status'=>$params['status'],'complete_date'=>time(),'message'=>$msg),array('key'=>$params['key']));
    }

}
